package com.hou.shop.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hou.common.constant.ProductConstant;
import com.hou.shop.product.dao.AttrAttrgroupRelationDao;
import com.hou.shop.product.dao.AttrGroupDao;
import com.hou.shop.product.dao.CategoryDao;
import com.hou.shop.product.entity.AttrAttrgroupRelationEntity;
import com.hou.shop.product.entity.AttrGroupEntity;
import com.hou.shop.product.entity.CategoryEntity;
import com.hou.shop.product.service.CategoryService;
import com.hou.shop.product.vo.AttrVo;
import com.hou.shop.product.vo.AttrRespVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hou.common.utils.PageUtils;
import com.hou.common.utils.Query;

import com.hou.shop.product.dao.AttrDao;
import com.hou.shop.product.entity.AttrEntity;
import com.hou.shop.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveDetail(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();

        // 属性复制
        BeanUtils.copyProperties(attr, attrEntity);

        // 保存属性表
        this.save(attrEntity);

        // 保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType() && attr.getAttrGroupId() != null) {
            // 构建属性分组实例
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            // 保存属性分组关系表
            relationDao.insert(relationEntity);
        }

    }

    // 条件查询获取信息
    @Override
    public PageUtils getPage(Map<String, Object> params, Long catId, String type) {
        String key = (String) params.get("key");

        // 条件构造器
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        // 决定获取销售属性还是规格参数
        wrapper.eq("attr_type", type.equals("base") ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getType());

        // 根据attrid的值判断是获取全部信息还是指定id信息
        if (catId != 0) {
            wrapper.eq("catelog_id", catId);
        }

        // 判断是否进行模糊查询
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrRespVo> otherData = records.stream().map((obj) -> {
            AttrRespVo catlogAttrGroupAttrVo = new AttrRespVo();
            BeanUtils.copyProperties(obj, catlogAttrGroupAttrVo);

            if (type.equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getFront_typpe())) {
                // 获取组id
                AttrAttrgroupRelationEntity relation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", obj.getAttrId()));
                if (!StringUtils.isEmpty(relation) && relation.getAttrId() != null) {
                    Long attrGroupId = relation.getAttrGroupId();
                    // 查询组名称
                    AttrGroupEntity attrGroup = attrGroupDao.selectById(attrGroupId);
                    catlogAttrGroupAttrVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }


            CategoryEntity category = categoryDao.selectById(obj.getCatelogId());
            if (!StringUtils.isEmpty(category)) {
                // 查询分类信息
                catlogAttrGroupAttrVo.setCatelogName(category.getName());
            }

            return catlogAttrGroupAttrVo;
        }).collect(Collectors.toList());

        pageUtils.setList(otherData);

        // 销售属性/规格参数数据返回
        return pageUtils;
    }

    // 获取指定id信息
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo respVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);


        if (respVo.getAttrType()==ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType()) {
            //1、设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (attrgroupRelation != null) {
                respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if (attrGroupEntity != null) {
                    respVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.getPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCatelogName(categoryEntity.getName());
        }


        return respVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType()){
            //1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){

                relationDao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));

            }else{
                relationDao.insert(relationEntity);
            }
        }


    }

    // 获取分组关联关系
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {

        List<AttrAttrgroupRelationEntity> entities = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        // 非空判断
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }

        List<AttrEntity> attrEntities = this.listByIds(attrIds);

        return attrEntities;
    }

    // 获取当前分组没有关联的所有属性
    @Override
    public PageUtils getNoAttrInfo(Long attrgroupId, Map<String, Object> params) {

        // 只能关联自己所属分类里面的属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 只能获取别的分组没有引用的信息

        // 当前分类id下所有分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 获取分组id
        List<Long> attrGroup = group.stream().map((obj) -> {
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());

        // 上方分组id关联属性
        List<AttrAttrgroupRelationEntity> excludeData = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", attrGroup));
        // 获取需要排除的属性id
        List<Long> excludeDataId = excludeData.stream().map((obj) -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        // 将数据排除出去
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getType());
        if (excludeDataId != null && excludeDataId.size() != 0) {
            wrapper.notIn("attr_id", excludeDataId);
        }
        // 模糊查询
        String key = (String) params.get("key");
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);

    }


}